<!-- 端对端的私聊视频 -->
<template>
  <div>
    <div class='p2pContainer'>
      <div class="other">
        <video ref='otherVideo'
               autoPlay
               style="height:100%;width:100%"
               playsInline />
      </div>
      <div class="me">
        <video ref='meVideo'
               autoPlay
               style="height:100%;width:100%"
               playsInline />
      </div>

    </div>

    <!-- 视频遮罩层 -->
    <div class="shipin-container "
         :class="received?'':'wait-call-shipin'">

      <van-overlay :show="true"
                   duration="0.5">
        <div class="shipin-wrapper"
             @click.stop>

          <!-- 头部区域 -->
          <div class="shipin-head">
            <van-row>
              <van-col span="4">
                <van-icon class="iconfont"
                          class-prefix="icon-ali"
                          name="suoxiao"
                          size="20" />
              </van-col>
              <van-col span="10"
                       offset="4">等待对方接受邀请...</van-col>
              <van-col span="4"
                       offset="2">
                <van-icon class="iconfont"
                          class-prefix="icon-ali"
                          name="qiehuanshexiangtou"
                          size="20" />
              </van-col>
            </van-row>

          </div>
          <!-- 中间body -->
          <div class="shipin-body"
               v-if="!received">
            <div class="user-avater-style">
              <van-image width="100"
                         height="100"
                         radius="20"
                         src="https://img.yzcdn.cn/vant/cat.jpeg" />
            </div>
            <div class="user-name-style">
              <sapn>孤独的狼</sapn>
            </div>

          </div>
          <!-- 脚部区域 -->
          <div class="shipin-foot">
            <div class="maikefeng">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="mic-on"
                        size="26" />
            </div>
            <div class="dianhua">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="dianhuaguaduan"
                        @click="hungupShipin"
                        size="26" />
            </div>
            <div class="yangshengqi">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="dianhua"
                        @click="answering"
                        size="26" />
            </div>
            <div class="yangshengqi">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="closeyangshengqi"
                        size="26" />
            </div>

          </div>

        </div>
      </van-overlay>
    </div>
  </div>

</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    //这里存放数据
    return {
      // 对方谁打过来的视频
      to: '',
      //已经接听，正在通话
      received: false,
    }
  },
  //方法集合
  methods: {
    // 开始初始化视频拨打
    init () {
      // 开始调用拨打电话
      this.call();
    },
    call () {
      var that = this;
      const socket = this.$store.state.socket;
      var webrtcConfig = {
        type: 'shipin-call',
        // 媒体约束
        constraints: {
          audio: true,
          video: true
        },
        from: this.$socket.config.identity,
        to: this.to
      }
      //发起方发起webrtc通话请求
      Webrtc.init(socket).call(webrtcConfig, (webrtc) => {
        // 将webrtc 存起来
        that.$store.commit('setWebrtc', webrtc)

        // 最多等候15秒，如果对方不在线或没处理则会自动结束
        // let timeObj = setTimeout(() => {
        //   if (webrtc) {
        //     webrtc.releaseSource();
        //     that.$store.commit('setWebrtc', null);
        //   }
        //   // 跳转到用户页面
        //   that.$router.replace({ name: "UserChat", params: { identity: that.to } });
        // }, 15 * 1000);
        // that.$store.commit('setMaxDelayReceiveTime', timeObj)
      }, (localMediaStream, remoteMediaStream) => {
        that.$refs.meVideo.srcObject = localMediaStream;
        console.log("回调流信息", remoteMediaStream)
        that.$refs.otherVideo.srcObject = remoteMediaStream[0];
        // 去除遮罩层
        that.received = true;
      })
    },

    // 接收视频
    answering () {
      var that = this;
      const socket = this.$store.state.socket;
      var webrtcConfig = {
        type: 'shipin-call',
        constraints: {
          audio: true,
          video: true
        },
        from: this.$socket.config.identity,
        to: this.to
      }
      // 接收方准备接收发起方的请求
      Webrtc.init(socket).receive(webrtcConfig, (webrtc) => {
        // 将webrtc 存起来
        this.$store.commit('setWebrtc', webrtc);
        // 发送给发起方信令告知这边已经准备可以进行下一步
        let agreeCallMessage = new proto.com.ouyu.im.Message();
        agreeCallMessage.setFrom(webrtcConfig.from)
        agreeCallMessage.setTo(webrtcConfig.to)
        agreeCallMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
        agreeCallMessage.setContent(JSON.stringify({
          type: "agree-call",
        }));
        agreeCallMessage.setCreateTime(new Date().getTime());
        socket.send(agreeCallMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.WEBRTC_SIGNALING);
        let maxDelayReceiveTime = this.$store.state.maxDelayReceiveTime;
        clearTimeout(maxDelayReceiveTime);
      }, (localMediaStream, remoteMediaStream) => {
        console.log("回调流信息", remoteMediaStream)
        // 都准备好后进行渲染视频
        that.$refs.meVideo.srcObject = localMediaStream;
        that.$refs.otherVideo.srcObject = remoteMediaStream[0];
        that.received = true;
      });
    },

    hungupShipin () {
      // 通知对方
      const socket = this.$store.state.socket;
      var webrtc = this.$store.state.webrtc;

      // 发送一条挂断消息给对方
      let bayeMessage = new proto.com.ouyu.im.Message();
      bayeMessage.setFrom(this.$socket.config.identity)
      bayeMessage.setTo(this.to)
      bayeMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
      bayeMessage.setContent(JSON.stringify({
        type: "hungup-shipin",
      }));
      bayeMessage.setCreateTime(new Date().getTime());
      socket.send(bayeMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.WEBRTC_SIGNALING);
      // 释放资源
      if (webrtc) {
        webrtc.releaseSource();
        this.$store.commit('setWebrtc', null);
      }
      this.$router.replace({ name: "UserChat", params: { identity: this.to } });

    },

    // 监听视频挂断
    onmessage (data) {
      if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.WEBRTC_SIGNALING) {
        var contentType = data.message.getContentType();
        var content = {};
        if (contentType === SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT) {
          content = JSON.parse(data.message.getContent())
        }
        let webrtc = this.$store.state.webrtc;
        if (webrtc && content.type === 'hungup-shipin') {
          webrtc.releaseSource();
          this.$store.commit('setWebrtc', null);
          this.$router.replace({ name: "UserChat", params: { identity: this.to } });
        }

      }
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 监听事件
    this.$emitter.on('onmessage', this.onmessage);

    // 处理其他
    this.to = this.$route.params.identity;
    // 最多等候15秒，如果对方不在线或没处理则会自动结束
    let timeObj = setTimeout(() => {
      const webrtc = this.$store.state.webrtc;
      if (webrtc) {
        webrtc.releaseSource();
        this.$store.commit('setWebrtc', null);
      }
      // 跳转到用户页面
      this.$router.replace({ name: "UserChat", params: { identity: this.to } });
    }, 15 * 1000);
    this.$store.commit('setMaxDelayReceiveTime', timeObj)
    this.init();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  //生命周期 - 创建之前
  beforeCreate () {

  },
  //生命周期 - 挂载之前
  beforeMount () {

  },
  //生命周期 - 更新之前
  beforeUpdate () {

  },
  //生命周期 - 更新之后
  updated () {

  },
  //生命周期 - 销毁之前
  beforeUnmount () {

  },
  //生命周期 - 销毁完成
  unmounted () {
    this.$emitter.off('onmessage', this.onmessage);

  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () {

  }
}
</script>
<style lang='less' scoped>
//@import url(); 引入公共css类
.p2pContainer {
  position: relative;
  background: whitesmoke;
  height: 18.45rem;
  display: flex;
  justify-self: start;
  flex-direction: column;
  flex-wrap: nowrap;
  align-content: center;
  align-items: stretch;
  .other {
    width: 9.94rem;
    height: 7.8rem;
  }
  .me {
    width: 9.94rem;
    height: 7.8rem;
  }
}

.shipin-container /deep/ .van-overlay {
  background-color: transparent;
}
.wait-call-shipin /deep/ .van-overlay {
  background-image: linear-gradient(to bottom right, #646566, black);
}
.shipin-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  flex-wrap: nowrap;
  align-content: flex-start;
  height: 100%;
  .shipin-head {
    width: 100%;
    line-height: 60px;
    text-align: center;
    color: #fff;
  }
  .shipin-body {
    width: 3.2rem;
    height: 5rem;
    text-align: center;
    color: #fff;

    .user-avater-style {
    }
    .user-name-style {
      margin-top: 5px;
    }
  }
  .shipin-foot {
    display: flex;
    flex-wrap: nowrap;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    width: 100%;
    height: 2rem;

    .maikefeng {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
    .dianhua {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
    .jujie {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
    .yangshengqi {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
    .shexiangtou {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
  }
}
</style>